package com.qiyou.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONArray;

import com.qiyou.dao.factory.DaoFactory;
import com.qiyou.util.DBUtil;
import com.qiyou.util.LogUtil;

/**
 * 客户端获取活动列表
 */
@WebServlet(name = "ActivityListService", urlPatterns = { "/ActivityListService" })
public class ActivityListService extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private static final Logger log = LogUtil
            .getLogger(ActivityListService.class);

    public ActivityListService()
    {
        super();
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");

        // String sql =
        // "select `tb_activity`.acID, userFace, `tb_activity`.userID, acDate, acStartDate, acPlace, temp_table.joinedNum, `max` from tb_activity left outer join tb_user_info on `tb_activity`.userID=`tb_user_info`.userID, (select `tb_activity_invitation`.acID, count(`tb_activity_invitation`.userID) joinedNum from `tb_activity_invitation` group by `tb_activity_invitation`.acID) temp_table where temp_table.acID=`tb_activity`.acID";
        String sql = "select `tb_activity`.acID, userFace, `tb_activity`.userID, acDate, acStartDate, acPlace, count(`tb_activity_invitation`.userID) joinedNum, `max` from `tb_activity` left Outer join `tb_activity_invitation` on `tb_activity`.acID = `tb_activity_invitation`.acID, `tb_user_info` where `tb_activity`.userID = `tb_user_info`.userID group by `tb_activity`.acID";
        Connection conn = DaoFactory.getDatabase().getConnection();
        List<Map<String, Object>> result = null;
        try
        {
            result = DBUtil.queryForMap(conn, sql);
        }
        catch (SQLException e)
        {
            log.error(e);
        }
        finally
        {
            DBUtil.closeConnection(conn);
        }

        JSONArray questionjson = new JSONArray(result);
        String msg = questionjson.toString();
        PrintWriter out = response.getWriter();
        out.print(msg);
        out.flush();
        out.close();

        log.info("用户:" + request.getRemoteAddr() + ",访问了活动列表信息:" + msg);
    }
}
